package com.sh.舱壁模式;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class BulkheadService {
    private final ExecutorService executorService;

    // 构造函数，接收最大线程数并初始化线程池
    public BulkheadService(int maxThreads) {
        executorService = Executors.newFixedThreadPool(maxThreads);
    }

    // 执行任务的方法，传入资源对象
    public void executeTask(final Resource resource) {
//        executorService.submit(() -> resource.performOperation());
         // 故障隔离
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                resource.performOperation();
            }
        });
    }

    // 关闭线程池的方法
    public void shutdown() {
        executorService.shutdown();
        try {
            // 等待线程池中的任务执行完成，最多等待 10 秒
            if (!executorService.awaitTermination(10, TimeUnit.SECONDS)) {
                // 如果 10 秒内未完成，强制关闭线程池
                executorService.shutdownNow();
            }
        } catch (InterruptedException e) {
            // 如果等待过程中被中断，强制关闭线程池并重新设置中断标志
            executorService.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }
}